<template>
  <div class="btn_container">
    <button class="open-button" @click="changeShow">
      <slot></slot>
    </button>
    <div v-if="pageData.control.formShow" class="mask" @click.self="changeShow">
      <form class="form_box">
        <p class="title">导入</p>
        <input v-model="pageData.currency" placeholder="币种选择器" style="width: 98%;height: 50px;border-radius: 5px">
        <input ref="upload" class="upload" style="display: none" type="file" @change="fileUploaded"/>
        <div class="file_list"
             @dragleave="handleDragLeave"
             @drop="handleDrop"
             @dragover.prevent>
          <div v-show="!fileListIsPresent" class="file_tips" @click="upload">拖入文件,或点击上传</div>
          <ul>
            <li v-for="(item,$index) in pageData.fileList" :key="$index">
              <span class="file_name">{{ item.name }}</span><span class="del" @click="delFile($index)">删除</span>
            </li>
          </ul>
        </div>
        <div class="btn_group">
          <button class="open-button commit" type="button" @click="commit">提交</button>
          <button class="open-button cancel" type="button" @click="cancel">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "BatchRecharge",
  props: {
    // 上传地址
    url: {
      type: String,
      required: true
    },
    token: {
      type: String,
      required: true,
      default: ''
    },
    // 可选币种
    currency: {
      type: Array,
      required: true,
      default: () => ['CNY'],
      validator(value) {
        return value.every(item => typeof item === 'string');
      }
    },
    jyPassword: {
      type: String,
      required: true,
      default: ''
    }
  },
  computed: {
    fileListIsPresent() {
      return this.pageData.fileList && this.pageData.fileList.length > 0
    }
  },
  data() {
    return {
      pageData: {
        control: {
          formShow: false
        },
        fileList: [],
        currency: ''
      }
    }
  },
  methods: {
    changeShow() {
      this.pageData.control.formShow = !this.pageData.control.formShow
    },
    handleDrop(event) {
      event.preventDefault()
      const files = event.dataTransfer.files;
      this.pushFile(files[0])
    },
    pushFile(file) {
      if (this.pageData.fileList.length > 0) {
        this.pageData.fileList = []
      }
      this.pageData.fileList.push(file)
    },
    handleDragLeave() {
      //this.pageData.fileList = [];
    },
    delFile(index) {
      this.pageData.fileList.splice(index, 1)
    },
    commit() {
      if (this.pageData.currency && this.pageData.fileList.length > 0) {
        this.commitForm()
      } else {
        alert('缺少必要条件')
      }
    },
    cancel() {
      this.pageData.fileList = []
      this.pageData.currency = ''
      this.pageData.control.formShow = false
    },
    commitForm() {
      const file = this.pageData.fileList[0];
      console.log(file)
      // 构造 FormData 对象
      const formData = new FormData();
      formData.append('file', file); // 替换为实际文件对象
      formData.append('currency', this.pageData.currency);
      formData.append('jyPassword', this.jyPassword);
      try {
        console.log(formData.get("file"))
        // 发送请求
        const response = axios({
          method: 'post',
          url: this.url,
          headers: {
            'admin-auth-token': this.token,
          },
          data: formData,
          responseType: 'blob',
        });
        // 获取文件名（从响应头或默认值）
        let finalFileName = 'download.xlsx';
        response.then(res => {
          console.log("content-type", res.headers.get('content-type'))
          if (res?.headers?.get("content-type")) {
            let contentType = res.headers.get('content-type');
            if (contentType === 'application/octet-stream') {
              const blob = new Blob([res.data], {type: 'content-disposition'});
              const link = document.createElement('a');
              link.href = URL.createObjectURL(blob);
              link.download = finalFileName;
              link.click();
              // 释放 URL 对象
              URL.revokeObjectURL(link.href);
              this.pageData.control.formShow = false
            } else if (contentType === 'application/json') {
              let msgBlob = res.data;
              let reader = new FileReader();
              reader.onloadend = () => {
                alert(JSON.parse(reader.result)['message'])
              }
              reader.readAsText(msgBlob)
            }
          }
        })
      } catch (error) {
        console.error('请求失败:', error.response ? error.response.data : error.message);
      }
    },
    upload() {
      this.$refs.upload.click()
    },
    fileUploaded(event) {
      console.log('文件选择成功')
      if (event?.target?.files) {
        let files = event.target.files;
        if (files.length < 0) {
          console.error('上传失败,文件不存在')
        }
        this.pushFile(files[0])
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.btn_container {
  z-index: 99999;
}

.open-button {
  background-color: #2d8cf0;
  border: none;
  color: white;
  border-radius: 5px;
  padding: 5px 10px;
  min-width: 80px;
}

.mask {
  background-color: rgba(0, 0, 0, 0.15);
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  backdrop-filter: blur(1px);
}

.form_box {
  padding: 20px;
  box-sizing: border-box;
  position: absolute;
  width: 400px;
  height: 300px;
  border: 1px solid #e5e5e5;
  border-radius: 10px;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.07);
  top: 30%;
  left: 50%;
  margin-top: -50px;
  margin-left: -200px;
  background-color: white;
  display: flex;
  align-items: center;
  flex-direction: column;
  z-index: 99999;

  .title {
    width: 100%;
    font-size: 16px;
    color: #6a6a6a;
    margin-bottom: 10px;
  }

  .btn_group {
    .commit {
      margin-top: 10px;
      width: 50px;
      margin-right: 20px;
    }

    .cancel {
      width: 50px;
      background-color: #9c9c9c;
    }
  }
}

.file_list {
  margin-top: 20px;
  border-radius: 5px;
  border: 1px solid #b0b0b0;
  width: 100%;
  height: 100%;
  padding: 5px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: center;

  div {
    color: #565151;
  }

  .file_name {
    color: #565151;
  }

  .del {
    margin-left: 5px;
    color: #f86f6f;
    font-size: 12px;
    cursor: pointer;
  }

  .file_tips {
    cursor: pointer;
    font-size: 14px;
    color: #9c9c9c;
  }
}

</style>
